from fastapi import Request, FastAPI
from fastapi.responses import JSONResponse


class BusinessException(Exception):
    def __init__(self, code: int = 4001, message: str = "业务异常"):
        self.code = code
        self.message = message


def register_exceptions(app: FastAPI):
    @app.exception_handler(BusinessException)
    async def business_handler(request: Request, exc: BusinessException):
        return JSONResponse(status_code=200, content={"code": exc.code, "message": exc.message, "data": None})

    @app.exception_handler(Exception)
    async def global_handler(request: Request, exc: Exception):
        return JSONResponse(status_code=500, content={"code": 5000, "message": "系统错误", "data": None})

''' 
常规的异常处理器
from fastapi import HTTPException

if existing:
    raise HTTPException(status_code=400, detail="邮箱已存在")
    

使用自定义异常类
# main.py中注册异常处理器
register_exceptions(app)

# user.py中使用自定义异常类
from ..core.exception import BusinessException

if not user:
    raise BusinessException(code=4040, message="用户不存在")

'''